/*
 * Created on Feb 9, 2010
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.ia.neuralNetwork;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class Weight {
	
	 private static double[][] pesosCapa1;
	 private static double[][] pesosCapa2;
	
	 private static double biasWeight1 = 0;
	 private static double biasWeight2 = 0;
	 private static neuralNetwork nn = new neuralNetwork();
	
	 
	 Weight() {
	 	super();
	 	setbiasWeight();
	 	setWeightLayer_1();
		setWeightLayer_2(); 
	 }
	 
	 protected void setbiasWeight() {	 		 	
        Random r = new Random();
        biasWeight2 = randomizeWeights(-1, 1, r);
        biasWeight1 = randomizeWeights(-1, 1, r);     
    }

    public double getBiasCapa1() {
        return biasWeight1;
    }

    public double getBiasCapa2() {
        return biasWeight2;
    }

    public void setBiasCapa1(double b1) {
        biasWeight1 = b1;
    }

    public void setBiasCapa2(double b2) {
        biasWeight2 = b2;
    }

    static protected double randomizeWeights(double min, double max, Random r) {
        return (r.nextDouble() * (max - min)) + min;
    }
    
    protected void setWeightLayer1(int i,int x,double w) {
       pesosCapa1[i][x]=w;
    }
    
    protected void setWeightLayer2(int i,int x,double w) {
        pesosCapa2[i][x]=w;
    }
    
    protected double getWeightLayer1(int i,int x) {
        return pesosCapa1[i][x];
    }
    
    protected static double[][] getWeightLayer_1() {
        return pesosCapa1;
    }
    
    protected static double[][] getWeightLayer_2() {
        return pesosCapa2;
    }
    
    protected double getWeightLayer2(int i,int x) {
        return pesosCapa2[i][x];
    }
    
    protected static void setWeight(double[][] p1, double[][] p2) {
        pesosCapa1 = p1;
        pesosCapa2 = p2;
    }
    
    protected void setWeightLayer_1() {
    	
        Random r = new Random();
        
        
        double [][] pesos = new double[nn.getNeuronasEntrada()][nn.getNeuronasCapaOculta()];

        for (int l = 0; l < nn.getNeuronasCapaOculta(); l++) {
            for (int li = 0; li < nn.getNeuronasEntrada(); li++) {
                pesos[li][l] = randomizeWeights(-1, 1, r);
               
            }
           
        }
        	
        pesosCapa1 = pesos;
    }
   
    protected void setWeightLayer_2() {

       Random r = new Random();

        double [][]pesos = new double[nn.getNeuronasSalida()][nn.getNeuronasCapaOculta()];

        for (int n = 0; n < nn.getNeuronasSalida(); n++) {
            for (int i = 0; i < nn.getNeuronasCapaOculta(); i++) {
                pesos[n][i] = randomizeWeights(-1, 1, r);
            }
        }

        pesosCapa2 = pesos;
    }
    
	public void saveWeights(String path, String nombrefichero) {

		double[][] t1 = getWeightLayer_1();
		double[][] t2 = getWeightLayer_2();

		int OCULTA = nn.getNeuronasCapaOculta();
		int ENTRADA = nn.getNeuronasEntrada();
		int SALIDA = nn.getNeuronasSalida();

		// Validamos si existe el fichero
		String sFichero = path + nombrefichero;

		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(sFichero));

			bw.write("#0;" + getBiasCapa1() + ";" + getBiasCapa2() + "\n");

			// System.out.println("pesos capa 1");
			for (int l = 0; l <= OCULTA - 1; l++) {
				for (int li = 0; li <= ENTRADA - 1; li++) {
					bw.write("#1;" + li + ";" + l + ";" + t1[li][l] + "\n");
				}
			}

			for (int n = 0; n <= SALIDA - 1; n++) {
				for (int i = 0; i <= OCULTA - 1; i++) {
					bw.write("#2;" + n + ";" + i + ";" + t2[n][i] + "\n");
				}
			}

			// Hay que cerrar el fichero
			bw.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

	}
    
    
    public void loadWeight(String path,String nombrefichero){

		double[][] t1 = getWeightLayer_1();
		double[][] t2 = getWeightLayer_2();

		String fichero = path + nombrefichero;

		File existeFichero = new File(fichero);

		if (existeFichero.exists()) {

			File archivo = null;
			FileReader fr = null;
			BufferedReader br = null;

			try {
				// Apertura del fichero y creacion de BufferedReader para poder
				// hacer una lectura comoda (disponer del metodo readLine()).
				archivo = new File(fichero);
				fr = new FileReader(archivo);
				br = new BufferedReader(fr);

				String linea = "";

				String pe[] = null;

				int x = 0;
				int y = 0;
				double w = 0;

				// volvemos a leer el fichero y cargamos el array con cada una
				// de las lineas del fichero de patrones
				while ((linea = br.readLine()) != null) {

					pe = linea.split(";");

					if (pe[0].equals("#0")) {

						setBiasCapa1(Double.parseDouble(pe[1]));
						setBiasCapa2(Double.parseDouble(pe[2]));

					}

					if (pe[0].equals("#2")) {

						x = Integer.parseInt(pe[1]);
						y = Integer.parseInt(pe[2]);
						w = Double.parseDouble(pe[3]);

						t2[x][y] = w;

					}

					if (pe[0].equals("#1")) {

						x = Integer.parseInt(pe[1]);
						y = Integer.parseInt(pe[2]);
						w = Double.parseDouble(pe[3]);

						t1[x][y] = w;

					}

				}

				setWeight(t1, t2);

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// En el finally cerramos el fichero, para asegurarnos
				// que se cierra tanto si todo va bien como si salta
				// una excepcion.
				try {
					if (null != fr) {
						fr.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}

	}
}
